/*
 * Copyright (C) 2023 Coder.AN
 * Email: an.hongjun@foxmail.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "edge_tensor.h"
#include "edge_tensor_kernel.h"
#include <stdio.h>


__global__ void MapSegRes_kernel(const uint8_t* src, uint8_t* dst, size_t unit_count, uint8_t* map_list, uint8_t max_val)
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx >= unit_count) return;
    if (src[idx] >= max_val) return;
    dst[idx] = map_list[src[idx]];
}

void MapSegRes(const uint8_t* src, uint8_t* dst, size_t unit_count, std::vector<uint8_t> map_list)
{
    uint8_t* map_list_gpu;
    CHECK(cudaMalloc(&map_list_gpu, map_list.size()));
    CHECK(cudaMemcpy(map_list_gpu, &map_list[0], map_list.size(), cudaMemcpyHostToDevice));
    dim3 block(1024);
    dim3 grid((unit_count - 1) / block.x + 1);
    MapSegRes_kernel<<<grid, block>>>(src, dst, unit_count, map_list_gpu, (uint8_t)map_list.size());
    CHECK(cudaDeviceSynchronize());
    CHECK(cudaFree(map_list_gpu));
    return;
}